package cn.wit.summit.chwan.dot;


import org.greenrobot.eventbus.EventBus;

import java.util.List;

import cn.wit.summit.chwan.models.db.DotRequestTable;
import cn.wit.summit.chwan.models.event.DotEvent;
import cn.wit.summit.chwan.models.greendao.gen.DotRequestTableDao;
import cn.wit.summit.chwan.ui.base.MyApplication;

/**
 * Created by Alan on 2017/12/27.
 */

public class DotRequestManager {

    private static DotRequestManager downloadManager;
    private DotRequestTableDao mDotRequestTableDao;

    private DotRequestManager(){
        mDotRequestTableDao = MyApplication.getMyApplication().getmDotRequestTableDao();
    }

    public static DotRequestManager getInstance(){
        if(downloadManager==null) downloadManager = new DotRequestManager();
        return downloadManager;
    }

    /**
     * 获取所有
     * */
    public List<DotRequestTable> getAllDot() {
        return mDotRequestTableDao.queryBuilder().list();
    }

    public DotRequestTable getDotById(long Id) {
        return mDotRequestTableDao.queryBuilder().where(DotRequestTableDao.Properties.Id.eq(Id)).unique();
    }

    /**
     * 插入
     * */
    public void insertDownload(DotRequestTable dotRequestTable) {
        if (dotRequestTable == null) return;
//        if (isExist(dotRequestTable.getId())) {
//            updataDownload(dotRequestTable);
//        } else {
            mDotRequestTableDao.insertOrReplace(dotRequestTable);
        EventBus.getDefault().post(new DotEvent());
//        }
    }

    /**
     * 更新
     * */
    public void updataDownload(DotRequestTable dotRequestTable) {
        if (dotRequestTable == null) return;
        mDotRequestTableDao.update(dotRequestTable);
    }

    /**
     * 删除
     * */
    public void deleteDownload(long id) {
        DotRequestTable temp = mDotRequestTableDao.queryBuilder()
                .where(DotRequestTableDao.Properties.Id.eq(id)).unique();
        if (temp!=null) {
            mDotRequestTableDao.delete(temp);
        }
    }

    public void deleteDownloadAll() {
        mDotRequestTableDao.deleteAll();
    }

    public void deleteById(Long id) {
        mDotRequestTableDao.deleteByKey(id);
    }

    /**
     * 下载任务是否存在
     * */
    public boolean isExist(long id) {
        DotRequestTable temp = mDotRequestTableDao.queryBuilder()
                .where(DotRequestTableDao.Properties.Id.eq(id)).unique();
        if (temp==null)
            return false;
        else
            return true;
    }
}
